14. Exercise: Implement touchMove()
22 15 AAK TouchMove SC V2
Android Developer Documentation
Exercise
In this exercise you are going to implement touchMove().
- At the class level, add a
touchTolerancevariable and set it toViewConfiguration.get(context).scaledTouchSlop.
private val touchTolerance = ViewConfiguration.get(context).scaledTouchSlop
- Define the
touchMove()method. Calculate the traveled distance (dx,dy), create a curve between the two points and store it inpath, update the runningcurrentXandcurrentYtally, and draw thepath. Then callinvalidate()to force redrawing of the screen with the updatedpath.
private fun touchMove() {
val dx = Math.abs(motionTouchEventX - currentX)
val dy = Math.abs(motionTouchEventY - currentY)
if (dx >= touchTolerance || dy >= touchTolerance) {
// QuadTo() adds a quadratic bezier from the last point,
// approaching control point (x1,y1), and ending at (x2,y2).
path.quadTo(currentX, currentY, (motionTouchEventX + currentX) / 2, (motionTouchEventY + currentY) / 2)
currentX = motionTouchEventX
currentY = motionTouchEventY
// Draw the path in the extra bitmap to cache it.
extraCanvas.drawPath(path, paint)
}
invalidate()
}
In more detail, this is what you will be doing in code:
- Calculate the distance that has been moved (
dx,dy). - If the movement was further than the touch tolerance, add a segment to the path.
- Set the starting point for the next segment to the endpoint of this segment.
- Using
quadTo()instead oflineTo()create a smoothly drawn line without corners. See Bezier Curves. - Call
invalidate()to (eventually callonDraw()and) redraw the view.